/*
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2device.gameserver.model.events.tvt;

import java.util.ArrayList;
import java.util.LinkedList;

import com.l2device.gameserver.Announcements;
import com.l2device.gameserver.Config;
import com.l2device.gameserver.datatables.DoorTable;
import com.l2device.gameserver.model.actor.instance.L2DoorInstance;
import com.l2device.gameserver.model.actor.instance.L2PcInstance;

/**
 * @author Anarchy
 */
public class TvTEvent implements IEvent
{
       public ArrayList<L2PcInstance> _players;
       private EventState _state = EventState.INACTIVE;
       private final ArrayList<EventTeam> _teams;
       private final ArrayList<L2DoorInstance> _doors;
      
       public TvTEvent()
       {
               _players = new ArrayList<>();
               _teams = new ArrayList<>();
               _doors = new ArrayList<>();
       }
      
       @Override
       public void runEvent()
       {
               if (EventManager.getInstance().getCurrentEvent() != null)
               {
            	   return;
               }
              
               EventManager.getInstance().setCurrentEvent(this);
              
               Announcements.announceToAll("TvT: Регистрация на ивент доступна в течении " + Config.TVT_REGISTRATION_TIME + " минут");
               _state = EventState.REGISTERING;
              
               sleep(Config.TVT_REGISTRATION_TIME); //Время указывается в минутах
              
               if (!check())
               {
            	   EventManager.getInstance().setCurrentEvent(null);
            	   return;
               }
              
               Announcements.announceToAll("TvT: Регистрация на ивент закрыта.Команды будут перемещены в колизей через 1 минуту");
               _state = EventState.RUNNING;
              
               sleep(1); //Время указывается в минутах
              
               split();
              
               for (EventTeam et : _teams)
               {
            	   et.teleportTeam(Config.TVT_TEAMS_DATA.get(et.getName())[0], Config.TVT_TEAMS_DATA.get(et.getName())[1], Config.TVT_TEAMS_DATA.get(et.getName())[2], true);
            	   et.paralize(true);
               }
               closeDoors();
               Announcements.announceToAll("TvT: Команды перемещены в колизей. Битва начнется через 1 минуту");
              
               sleep(1); //Время указывается в минутах
              
               for (EventTeam et : _teams)
               {
                       et.paralize(false);
               }
               Announcements.announceToAll("TvT: Битва началась!");
               Announcements.announceToAll("TvT: Ивент проходит " + Config.TVT_TIME + " минут");
               sleep(Config.TVT_TIME); //Время указывается в минутах
              
               rewardAndClear();
               openDoors();
               _state = EventState.INACTIVE;
              
               EventManager.getInstance().setCurrentEvent(null);
       }
      
       private void openDoors()
       {
               if (_doors.isEmpty())
               {
                       for (int i : Config.TVT_DOORS)
                       {
                               L2DoorInstance door = DoorTable.getInstance().getDoor(i);
                               door.openMe();
                       }
               }
               else
               {
                       for (L2DoorInstance door : _doors)
                       {
                               door.deleteMe();
                       }
               }
       }
      
       private static void closeDoors()
       {
               for (int i : Config.TVT_DOORS)
               {
                       L2DoorInstance door = DoorTable.getInstance().getDoor(i);
                       door.closeMe();
               }
       }
      
       public void rewardAndClear()
       {
               int i = 0;
               EventTeam winner = null;
              
               for (EventTeam et : _teams)
               {
                       et.teleportTeam(82698, 148638, -3473, true);
                      
                       for (L2PcInstance p : et.getPlayers())
                       {
                               EventCommons.getInstance().removePlayer(p);
                       }
                      
                       if (et.getPoints() > i)
                       {
                               i = et.getPoints();
                               winner = et;
                       }
               }
              
               if (winner != null)
               {
                       for (int ii : Config.TVT_EVENT_REWARDS.keySet())
                       {
                    	   winner.rewardTeam(ii, Config.TVT_EVENT_REWARDS.get(ii));
                       }
                       Announcements.announceToAll("TvT: Команда " + winner.getName() + " победила.");
               }
               else
            	   Announcements.announceToAll("TvT: Ивент закончился в ничью.");
               return;
       }
      
       public boolean check()
       {
               if (EventCommons.getInstance().getRegisteredPlayersSize(TvTEvent.class) < Config.TVT_TEAMS_DATA.size() * 1)
               {
                       Announcements.announceToAll("TvT: Ивент отменен из-за нехватки участников.");
                       EventCommons.getInstance().removeRegisteredPlayers(TvTEvent.class);
                       _state = EventState.INACTIVE;
                       return false;
               }
              
               return true;
       }
      
       public void split()
       {
               int i = Config.TVT_TEAMS_DATA.size() - 1;
               LinkedList<LinkedList<L2PcInstance>> temp = new LinkedList<>();
              
               for (int ii = Config.TVT_TEAMS_DATA.size(); ii > 0; ii--)
               {
                       LinkedList<L2PcInstance> t = new LinkedList<>();
                       temp.add(t);
               }
              
               for (L2PcInstance p : EventCommons.getInstance().getRegisteredPlayers(TvTEvent.class))
               {
                       temp.get(i).add(p);
                       i--;
                      
                       if (i == -1)
                       {
                               i = Config.TVT_TEAMS_DATA.size();
                       }
                       EventCommons.getInstance().addPlayer(p, this);
               }
              
               for (String s : Config.TVT_TEAMS_DATA.keySet())
               {
                       EventTeam et = new EventTeam(temp.getLast(), s, 0, new int[]
                       {
                               Config.TVT_TEAMS_DATA.get(s)[0], Config.TVT_TEAMS_DATA.get(s)[1], Config.TVT_TEAMS_DATA.get(s)[2]
                       });
                       temp.remove(temp.getLast());
                      
                       _teams.add(et);
               }
       }
      
       private static void sleep(int seconds)
       {
    	   try
    	   {
    		   Thread.sleep(seconds * 60000);
    	   }
    	   catch (InterruptedException e)
    	   {
    		   e.printStackTrace();
    	   }
       }
      
       @Override
       public EventState getState()
       {
               return _state;
       }
      
       @Override
       public String getTimes()
       {
               return Config.TVT_EVENT_TIMES;
       }
      
       @Override
       public int getId()
       {
               return 1;
       }
}